
package com.leaves.modular.buspicturemanager.service.impl;

import java.util.Date;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leaves.common.operator.OperatorManager;
import com.leaves.core.consts.CommonConstant;
import com.leaves.core.context.login.LoginContextHolder;
import com.leaves.core.enums.CommonStatusEnum;
import com.leaves.core.exception.ServiceException;
import com.leaves.core.factory.PageFactory;
import com.leaves.core.pojo.page.PageResult;
import com.leaves.core.util.CopyUtil;
import com.leaves.core.util.PastTimeFormatUtil;
import com.leaves.core.util.RedisUtil;
import com.leaves.modular.buspicturefabulous.entity.BusPictureFabulous;
import com.leaves.modular.buspicturefabulous.param.BusPictureFabulousParam;
import com.leaves.modular.buspicturefabulous.service.BusPictureFabulousService;
import com.leaves.modular.buspicturemanager.entity.BusPictureManager;
import com.leaves.modular.buspicturemanager.entity.BusPictureManagerDto;
import com.leaves.modular.buspicturemanager.entity.CategoryPicture;
import com.leaves.modular.buspicturemanager.enums.BusPictureManagerExceptionEnum;
import com.leaves.modular.buspicturemanager.mapper.BusPictureManagerMapper;
import com.leaves.modular.buspicturemanager.param.BusPictureManagerParam;
import com.leaves.modular.buspicturemanager.service.BusPictureManagerService;
import com.leaves.sys.events.CommonEvent;
import com.leaves.sys.modular.dict.entity.SysDictType;
import com.leaves.sys.modular.dict.service.SysDictDataService;
import com.leaves.sys.modular.dict.service.SysDictTypeService;
import com.leaves.sys.modular.file.entity.SysFileInfo;
import com.leaves.sys.modular.file.param.SysFileInfoParam;
import com.leaves.sys.modular.file.service.SysFileInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 图片管理service接口实现类
 *
 * @author 寻叶人
 * @date 2022-03-27 22:05:15
 */
@Service
public class BusPictureManagerServiceImpl extends ServiceImpl<BusPictureManagerMapper, BusPictureManager> implements BusPictureManagerService {
    @Resource
    private SysDictTypeService sysDictTypeService;
    @Resource
    private SysDictDataService sysDictDataService;
    @Resource
    private SysFileInfoService sysFileInfoService;

    @Resource
    private BusPictureFabulousService busPictureFabulousService;

    @Override
    public PageResult<BusPictureManager> page(BusPictureManagerParam busPictureManagerParam) {
        QueryWrapper<BusPictureManager> queryWrapper = new QueryWrapper<>();
        Long userId = LoginContextHolder.me().getSysLoginUser().getId();

        boolean superAdmin = LoginContextHolder.me().isSuperAdmin();
        if (!superAdmin){
            queryWrapper.lambda().eq(BusPictureManager::getCreateUser, userId);
        }

        if (ObjectUtil.isNotNull(busPictureManagerParam)) {

            // 根据图片类型 查询
            if (ObjectUtil.isNotEmpty(busPictureManagerParam.getPrictureType())) {
                queryWrapper.lambda().eq(BusPictureManager::getPrictureType, busPictureManagerParam.getPrictureType());
            }
            // 根据描述 查询
            if (ObjectUtil.isNotEmpty(busPictureManagerParam.getPictureDescribe())) {
                queryWrapper.lambda().eq(BusPictureManager::getPictureDescribe, busPictureManagerParam.getPictureDescribe());
            }

        }
        queryWrapper.lambda().orderByDesc(BusPictureManager::getCreateTime);
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }


    @Override
    public void save(BusPictureManagerParam busPictureManagerParam) {
        List<Long> fileIdList = busPictureManagerParam.getFileIdList();
        List<BusPictureManager> busPictureManagers = CollectionUtil.newArrayList();
        List<SysFileInfo> sysFileInfos = CollectionUtil.newArrayList();

        String username = LoginContextHolder.me().getSysLoginUser().getUsername();
        for (Long fileId : fileIdList) {
            SysFileInfo fileInfo = sysFileInfoService.getById(fileId);
            BusPictureManager busPictureManager = new BusPictureManager();
            BeanUtil.copyProperties(busPictureManagerParam, busPictureManager);
            busPictureManager.setFileId(fileId);
            busPictureManager.setNumberLikes(0);
            busPictureManager.setPictureName(fileInfo.getFileOriginName());
            busPictureManager.setCreateUserName(username);
            busPictureManagers.add(busPictureManager);
            fileInfo.setBusinessIdentification("BusPictureManagerService");
            sysFileInfos.add(fileInfo);
        }
        sysFileInfoService.updateBatchById(sysFileInfos);
        this.saveBatch(busPictureManagers);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BusPictureManagerParam> busPictureManagerParamList) {
        busPictureManagerParamList.forEach(busPictureManagerParam -> {
            BusPictureManager busPictureManager = this.queryBusPictureManager(busPictureManagerParam);
            Long fileId = busPictureManager.getFileId();
            //删除文件
            SysFileInfoParam sysFileInfoParam = new SysFileInfoParam();
            sysFileInfoParam.setId(fileId);
            sysFileInfoService.delete(sysFileInfoParam);
            //删除点赞记录
            busPictureFabulousService.deleteRecord(busPictureManager.getId());

            this.removeById(busPictureManagerParam.getId());
        });
    }


    /**
     * 获取图片管理
     *
     * @author 寻叶人
     * @date 2022-03-27 22:05:15
     */
    private BusPictureManager queryBusPictureManager(BusPictureManagerParam busPictureManagerParam) {
        BusPictureManager busPictureManager = this.getById(busPictureManagerParam.getId());
        if (ObjectUtil.isNull(busPictureManager)) {
            throw new ServiceException(BusPictureManagerExceptionEnum.NOT_EXIST);
        }
        return busPictureManager;
    }


    @Override
    public List<Dict> getPictureType() {
        boolean exists = RedisUtil.exists(CommonConstant.PICTURE_TYPE_KEY);
        if (exists) {
            return RedisUtil.getCacheList(CommonConstant.PICTURE_TYPE_KEY);
        }
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictType::getCode, CommonConstant.PICTURE_TYPE);
        SysDictType sysDictType = sysDictTypeService.getOne(queryWrapper);
        if (ObjectUtil.isNotNull(sysDictType)) {
            Long typeId = sysDictType.getId();
            List<Dict> dictList = sysDictDataService.getDictDataListByDictTypeId(typeId);
            RedisUtil.setCacheList(CommonConstant.PICTURE_TYPE_KEY, dictList, 7 * 24 * 3600, TimeUnit.SECONDS);
            return dictList;
        }
        return CollectionUtil.newArrayList();
    }

    /**
     * 获取banner图片
     *
     * @author yubaoshan
     * @date 2020/6/7 22:15
     */
    @Override
    public List<BusPictureManagerDto> getBanners() {
        List<BusPictureManagerDto> busPictureManagerDtos = CollectionUtil.newArrayList();

        QueryWrapper<BusPictureManager> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(BusPictureManager::getCreateTime);
        queryWrapper.last("limit 5");
        List<BusPictureManager> busPictureManagerList = this.list(queryWrapper);

        if (CollectionUtil.isNotEmpty(busPictureManagerList)) {
            busPictureManagerDtos = CopyUtil.copyList(busPictureManagerList, BusPictureManagerDto.class);
            //加入我的点赞情况
            operatorList(busPictureManagerDtos);

        }
        return busPictureManagerDtos;
    }

    /**
     * 分类图片
     *
     * @return
     */
    @Override
    public List<CategoryPicture> categoryPicture() {
        List<CategoryPicture> result = CollectionUtil.newArrayList();

        List<Dict> typeList = this.getPictureType();
        if (CollectionUtil.isNotEmpty(typeList)) {
            for (Dict dict : typeList) {
                String code = Convert.toStr(dict.get(CommonConstant.CODE));
                String name = Convert.toStr(dict.get(CommonConstant.VALUE));
                List<BusPictureManagerDto> busPictureManagerDtos = this.baseMapper.getList(code, 3);
                if (CollectionUtil.isNotEmpty(busPictureManagerDtos)) {
                    //加入我的点赞情况
                    operatorList(busPictureManagerDtos);

                    CategoryPicture categoryPicture = new CategoryPicture();
                    categoryPicture.setPrictureType(code);
                    categoryPicture.setPrictureTypeName(name);
                    categoryPicture.setBusPictureManagerDtoList(busPictureManagerDtos);
                    result.add(categoryPicture);
                }
            }
        }
        return result;
    }

    //加入点赞情况
    private void operatorList(List<BusPictureManagerDto> busPictureManagerDtos) {
        Long userId = LoginContextHolder.me().getSysLoginUser().getId();
        busPictureManagerDtos.forEach(busPictureManagerDto -> {
             Long pictureId = busPictureManagerDto.getId();
            QueryWrapper<BusPictureFabulous> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(BusPictureFabulous::getCreateUser,userId);
            queryWrapper.lambda().eq(BusPictureFabulous::getPictureId,pictureId);
            int count = busPictureFabulousService.count(queryWrapper);
            busPictureManagerDto.setOwnFabulousStatus(count > 0);
        });
    }

    /**
     * 分类图片
     *
     * @return
     */
    @Override
    public PageResult<BusPictureManagerDto> searchCategoryPicture(BusPictureManagerParam busPictureManagerParam) {

        QueryWrapper<BusPictureManager> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(busPictureManagerParam)) {
            // 根据图片类型 查询
            if (ObjectUtil.isNotEmpty(busPictureManagerParam.getPrictureType())) {
                queryWrapper.lambda().eq(BusPictureManager::getPrictureType, busPictureManagerParam.getPrictureType());
            }

            if (ObjectUtil.isNotEmpty(busPictureManagerParam.getSaveTime())) {
                String saveTime = busPictureManagerParam.getSaveTime();
                String startTime = PastTimeFormatUtil.getStartTime(saveTime);
                String endTime = PastTimeFormatUtil.getendTime(saveTime);
                queryWrapper.lambda().between(BusPictureManager::getSaveTime, startTime, endTime);

            }
        }
        queryWrapper.lambda().orderByDesc(BusPictureManager::getCreateTime);
        PageResult<BusPictureManager> pageResult = new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
        List<BusPictureManager> busPictureManagers = pageResult.getRows();

        PageResult<BusPictureManagerDto> pageResultList = new PageResult<>();
        BeanUtil.copyProperties(pageResult, pageResultList);
        if (CollectionUtil.isNotEmpty(busPictureManagers)) {
            List<BusPictureManagerDto> busPictureManagerDtos = CopyUtil.copyList(busPictureManagers, BusPictureManagerDto.class);
            //加入我的点赞情况
            operatorList(busPictureManagerDtos);
            pageResultList.setRows(busPictureManagerDtos);
        }
        return pageResultList;

    }

    /**
     * 作品点赞
     *
     * @param busPictureFabulousParam
     */
    @Override
    public void pictureFabulous(BusPictureFabulousParam busPictureFabulousParam) {
        Long pictureId = busPictureFabulousParam.getPictureId();
        BusPictureManager busPictureManager = this.getById(pictureId);
        if (ObjectUtil.isNull(busPictureManager)) {
            throw new ServiceException(BusPictureManagerExceptionEnum.NOT_EXIST);
        }
        Long userId = LoginContextHolder.me().getSysLoginUser().getId();
        QueryWrapper<BusPictureFabulous> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BusPictureFabulous::getCreateUser,userId);
        queryWrapper.lambda().eq(BusPictureFabulous::getPictureId,pictureId);
        queryWrapper.last("limit 1");
        int count = busPictureFabulousService.count(queryWrapper);
        if (count > 0){
            throw new ServiceException(BusPictureManagerExceptionEnum.REPEAT_FABULOUS);
        }
        BusPictureFabulous busPictureFabulous = new BusPictureFabulous();
        busPictureFabulous.setPictureId(pictureId);
        busPictureFabulousService.save(busPictureFabulous);
        //异步刷新
        OperatorManager.me().updateNumberLikes(pictureId);

    }

    @Override
    public void freshNumber(Long pictureId) {
        this.baseMapper.freshNumber(pictureId);
    }
}
